package cn.edu.xmut.chen.zhlg.zhlg.message.mapper;

import cn.edu.xmut.chen.zhlg.zhlg.message.entity.PrivateChat;
import cn.edu.xmut.chen.zhlg.zhlg.message.entity.PrivateMessage;
import cn.edu.xmut.chen.zhlg.zhlg.message.result.ChatResult;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.util.Date;
import java.util.List;

@Mapper
public interface PrivateChatMapper extends BaseMapper<PrivateChat> {
    @Insert("INSERT INTO tb_private_chat(id, user1_id, user2_id, create_time) " +
            "VALUES(#{id}, #{user1Id}, #{user2Id}, #{createTime})")
    int insert(PrivateChat chat);

    @Select("SELECT * FROM tb_private_chat " +
            "WHERE user1_id = #{user1Id} " +
            "AND user2_id = #{user2Id}")
    PrivateChat selectByUserPair(@Param("user1Id") String user1Id, @Param("user2Id") String user2Id);

    @Update("UPDATE tb_private_chat " +
            "SET last_message_id = #{messageId}, last_message_time = #{time} " +
            "WHERE id = #{chatId}")
    void updateLastMessage(@Param("chatId") String chatId,
                           @Param("messageId") String messageId,
                           @Param("time") Date time);

    @Select({
            "SELECT * FROM tb_private_chat " +
                    "WHERE user1_id = #{userId} " +
                    "OR user2_id = #{userId} " +
                    "ORDER BY last_message_time DESC"
    })
    List<PrivateChat> selectByUserId(@Param("userId") String userId);

    @Select({
            "SELECT * FROM tb_private_chat " +
                    "WHERE id LIKE CONCAT('%', #{userId}, '%') " +
                    "ORDER BY create_time DESC " +
                    "LIMIT #{offset}, #{limit}"
    })
    List<PrivateChat> selectByUserIdWithLimit(
            @Param("userId") String userId,
            @Param("offset") int offset,
            @Param("limit") int limit
    );
}